package com.daigoudao.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.daigoudao.util.Constants;
import com.daigoudao.util.StringUtils;
import com.daigoudao.web.dao.ICanBuyDao;
import com.daigoudao.web.dao.ITransInfoDao;
import com.daigoudao.web.dao.IUserDao;
import com.daigoudao.web.model.AreaModel;
import com.daigoudao.web.model.CanBuyModel;
import com.daigoudao.web.model.CategoryModel;
import com.daigoudao.web.model.FollowModel;
import com.daigoudao.web.model.PurchaseRecord;
import com.daigoudao.web.model.UserAreaModel;
import com.daigoudao.web.model.UserCategoryModel;
import com.daigoudao.web.model.UserModel;
import com.daigoudao.web.service.IUserService;

public class UserServiceImpl implements IUserService {

	private IUserDao userDao;

	private ICanBuyDao canBuyDao;

	private ITransInfoDao transInfoDao;

	public void setTransInfoDao(ITransInfoDao transInfoDao) {
		this.transInfoDao = transInfoDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	public void setCanBuyDao(ICanBuyDao canBuyDao) {
		this.canBuyDao = canBuyDao;
	}

	public void deleteFollow(int followId) throws Exception {
		userDao.delFollowerByID(followId);
	}

	@Override
	public List<UserModel> getHotBrokerList(UserModel userModel)
			throws Exception {

		int loginUserid = userModel.getUserid();

		List<UserModel> list = new ArrayList<UserModel>();
		List<UserModel> hotList = userDao.getHotBrokerList(userModel);
		for (UserModel user : hotList) {
			int userId = user.getUserid();
			String starImg = this.getStarImg(user.getStar());
			List<AreaModel> areaList = userDao.getAreaListByUserId(userId);
			List<CategoryModel> cateList = userDao
					.getCategoryListByUserId(userId);

			if (0 != loginUserid) {
				FollowModel follow = new FollowModel();
				follow.setUserId(loginUserid);
				follow.setFollower(userId);

				int followId = userDao.getFollowCountByUserId(follow);
				user.setFollowId(followId);// 标志位作用
			}
			user.setStarImg(starImg);
			user.setAreaList(areaList);
			user.setCateList(cateList);
			list.add(user);
		}

		return list;
	}

	@Override
	public List<UserModel> getHotBrokerLista(UserModel userModel)
			throws Exception {
		List<UserModel> list = userDao.getHotBrokerList(userModel);
		return list;
	}

	@Override
	public boolean saveFollower(FollowModel follow) throws Exception {

		boolean flag = userDao.saveFollower(follow) == 1 ? true : false;
		follow.setIsAdd(1);
		flag = userDao.updateFollowCount(follow) == 1 ? true : false;

		return flag;
	}

	@Override
	public boolean delFollower(FollowModel follow) throws Exception {

		boolean flag = userDao.delFollower(follow) == 1 ? true : false;
		flag = userDao.updateFollowCount(follow) == 1 ? true : false;

		return flag;
	}

	@Override
	public int getBrokerCount(UserModel userModel) throws Exception {
		return userDao.getBrokerCount(userModel);
	}

	@Override
	public List<UserModel> getBrokerList(UserModel userModel) throws Exception {

		int loginUserid = userModel.getUserid();
		List<UserModel> list = new ArrayList<UserModel>();
		List<UserModel> brokerList = userDao.getBrokerList(userModel);

		for (UserModel user : brokerList) {
			int userId = user.getUserid();

			String starImg = this.getStarImg(user.getStar());
			List<AreaModel> areaList = userDao.getAreaListByUserId(userId);
			CanBuyModel queryModel = new CanBuyModel();
			queryModel.setStatus(0);
			queryModel.setIsOpen(0);
			queryModel.getUser().setUserid(user.getUserid());
			queryModel.setPageSize(3);
			List<CanBuyModel> canBuyList = canBuyDao.queryCanBuys(queryModel);
			List<CategoryModel> cateList = userDao
					.getCategoryListByUserId(userId);

			if (0 != loginUserid) {
				FollowModel follow = new FollowModel();
				follow.setUserId(loginUserid);
				follow.setFollower(userId);

				int followId = userDao.getFollowCountByUserId(follow);
				user.setFollowId(followId);// 标志位作用
			}

			user.setStarImg(starImg);
			user.setAreaList(areaList);
			user.setCanBuyList(canBuyList);
			user.setCateList(cateList);
			list.add(user);
		}
		return list;
	}

	@Override
	public List<UserModel> getBrokerLista(UserModel user) throws Exception {

		List<UserModel> list = userDao.getBrokerList(user);

		return list;
	}

	public List<UserModel> getFollowList(UserModel user) throws Exception {
		return userDao.getFollowList(user);
	}

	public void cancelFollow(int followid) throws Exception {

	}

	@Override
	public UserModel saveUser(UserModel userModel) throws Exception {

		UserModel _userModel = null;

		String pwd = userModel.getPassword();
		pwd = StringUtils.pwdEncode(pwd);
		userModel.setPassword(pwd);

		boolean flag = userDao.saveUserLogin(userModel) == 1 ? true : false;

		if (flag) {
			String mail = userModel.getEmail();
			flag = userDao.saveUser(mail) == 1 ? true : false;
			userDao.initUserAttr(userModel.getUserid());

			_userModel = userDao.getUserLogin(userModel);
			_userModel.setPassword(null);
			_userModel.setNickName(mail);
		}

		return _userModel;
	}

	@Override
	public UserModel getUserLogin(UserModel userModel) throws Exception {

		String pwd = userModel.getPassword();
		pwd = StringUtils.pwdEncode(pwd);
		UserModel _userModel = userDao.getUserLogin(userModel);

		if (_userModel != null) {
			String _pwd = _userModel.getPassword();
			if (pwd.equals(_pwd)) {

				_userModel.setPassword(null);
				String nickName = _userModel.getNickName();

				if (nickName == null || "".equals(nickName)) {
					nickName = _userModel.getEmail();
					_userModel.setNickName(nickName);
				}
			} else {
				_userModel = null;
			}
		}
		return _userModel;
	}

	@Override
	public boolean updateUserLogin(UserModel userModel) throws Exception {

		boolean result = userDao.updateUserLogin(userModel) == 1 ? true : false;

		return result;
	}

	@Override
	public int updateUserPasswd(int userid, String oldPasswd, String newPasswd) {
		String passwd = userDao.getUserPasswd(userid);
		// MD5处理
		oldPasswd = StringUtils.pwdEncode(oldPasswd);
		// 原密码错误
		if (!passwd.equals(oldPasswd)) {
			return -1;
		}

		UserModel model = new UserModel();
		model.setUserid(userid);

		// 加密处理
		newPasswd = StringUtils.pwdEncode(newPasswd);
		model.setPassword(newPasswd);

		int result = userDao.updateUserPasswd(model);
		if (result == 1) {
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public boolean getSameEmail(String email) throws Exception {

		return userDao.getSameEmail(email) == 1 ? true : false;
	}

	@Override
	public UserModel getUserBaseInfoByID(int userid) {
		return userDao.getUserByID(userid);
	}

	/**
	 * 更新用户的基本信息
	 */
	@Override
	public void updateUserInfo(UserModel userModel) {
		userDao.updateUser(userModel);
	}

	@Override
	public UserModel getBrokerDetail(FollowModel follow) throws Exception {

		int userId = follow.getFollower();
		int luserId = follow.getUserId();

		UserModel userModel = userDao.getUserByID(userId);

		String starImg = this.getStarImg(userModel.getStar());
		CanBuyModel queryModel = new CanBuyModel();
		queryModel.setStatus(0);
		queryModel.setIsOpen(0);
		queryModel.setPageSize(follow.getPageSize());
		queryModel.setStartIndex(follow.getStartIndex());
		queryModel.getUser().setUserid(userId);
		List<CanBuyModel> canBuyList = canBuyDao.queryCanBuys(queryModel);
		for (CanBuyModel product : canBuyList) {
			PurchaseRecord record = new PurchaseRecord();
			record.setProductId(product.getCanId());
			int transNum = transInfoDao.getPurhcaseRecordCount(record);
			product.setTransNum(transNum);
		}
		int canBuyCount = canBuyDao.getCanBuyCount(queryModel);
		List<AreaModel> areaList = userDao.getAreaListByUserId(userId);
		List<CategoryModel> cateList = userDao.getCategoryListByUserId(userId);

		// 登录用户是否是关注者
		if (luserId != 0) {
			int followCount = userDao.getFollowCountByUserId(follow);
			userModel.setFollowId(followCount);// 1表示登录用户是关注者,followId此处重用起标志作用
		}

		userModel.setStarImg(starImg);
		userModel.setCanBuyList(canBuyList);
		userModel.setAreaList(areaList);
		userModel.setCateList(cateList);
		userModel.setCanBuyCount(canBuyCount);

		return userModel;
	}

	private String getStarImg(int star) {
		String starImg = Constants.STAR_S1;
		switch (star) {
		case 2:
			starImg = Constants.STAR_S2;
			break;
		case 3:
			starImg = Constants.STAR_S3;
			break;
		case 4:
			starImg = Constants.STAR_S4;
			break;
		case 5:
			starImg = Constants.STAR_S5;
			break;
		case 6:
			starImg = Constants.STAR_S6;
			break;
		case 7:
			starImg = Constants.STAR_S7;
			break;
		case 8:
			starImg = Constants.STAR_S8;
			break;
		case 9:
			starImg = Constants.STAR_S9;
			break;
		case 10:
			starImg = Constants.STAR_S10;
			break;
		}
		return starImg;
	}

	@Override
	public boolean getFollowCountByUserId(FollowModel follow) throws Exception {

		return userDao.getFollowCountByUserId(follow) == 1 ? true : false;
	}

	public boolean updateUserByEmail(UserModel userModel) throws Exception {

		return userDao.updateUserByEmail(userModel) == 1 ? true : false;
	}

	public int getCheckUserPwd(UserModel userModel) throws Exception {

		UserModel user = userDao.getCheckUserPwd(userModel);
		String validCode = user.getValidCode();
		String v = userModel.getValidCode();

		long time = System.currentTimeMillis();
		long sendTime = user.getSendTime();
		time = time - sendTime;

		if (validCode == null || !validCode.equals(v)) {
			return 0;
		}
		if (86400000 < time) {
			return 1;
		}

		return 2;
	}

	public boolean updateUserPwd(UserModel userModel) throws Exception {

		String pwd = userModel.getPassword();
		pwd = StringUtils.pwdEncode(pwd);
		userModel.setPassword(pwd);
		userDao.updateUserByEmail(userModel);
		return userDao.updatePassword(userModel) == 1 ? true : false;
	}

	@Override
	public boolean updateBrokerScore() throws Exception {
		boolean result = false;

		List<UserModel> list = userDao.getBrokerLista();
		if (list != null && !list.isEmpty()) {
			for (UserModel userModel : list) {
				int userId = userModel.getUserid();

				int transScore = this.getTransScore(userId);
				int evaluateScore = this.getEvaluateScore(userId);
				int avgSendTimeScore = this.getAvgSendTimeScore(userId);

				int score = (int) (transScore * 0.4 + evaluateScore * 0.4 + avgSendTimeScore * 0.2);
				int star = this.getStarByScore(score);
				userModel.setScore(score);
				userModel.setStar(star);

				result = userDao.updateBrokerScore(userModel) == 1 ? true
						: false;
			}
		}

		return result;
	}

	public int getTransScore(int userId) throws Exception {
		int score = 0;
		int n = userDao.getTransCount(userId);
		if (n >= 900) {
			score = 100;
		} else if (n >= 100) {
			score = (int) ((n / 1000f) * 40 + 60);
		} else if (n >= 10) {
			score = (int) ((n / 100f) * 30 + 34);
		} else {
			score = (int) ((n / 10f) * 37);
		}

		return score;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public int getEvaluateScore(int userId) throws Exception {
		int score = 0;
		Map map = new HashMap();
		map.put("userId", userId);
		map.put("level", 0);
		float evaluateCount = (float) userDao.getEvaluateCount(map);

		map.put("level", 1);
		int goodEvaluateCount = userDao.getEvaluateCount(map);

		map.put("level", 3);
		int notGoodEvaluateCount = userDao.getEvaluateCount(map);

		float v = goodEvaluateCount / evaluateCount;
		float nv = notGoodEvaluateCount / evaluateCount;
		if (v >= 0.98) {
			score = 100;
		} else if (v >= 0.95) {
			score = 60;
		} else if (v >= 0.9) {
			score = 40;
		} else if (v >= 0.8) {
			score = 0;
		} else {
			score = -50;
		}

		if (nv < 0.03) {
			score = (int) (score - (nv * 1000));
		} else {
			score = score - (notGoodEvaluateCount * 10);
		}

		if (score < -100) {
			score = -100;
		}

		return score;
	}

	public int getAvgSendTimeScore(int userId) throws Exception {
		int score = 0;
		int minute = userDao.getAvgSendTime(userId);
		if (minute <= 4320) {
			score = 100;
		} else if (minute <= 10080) {
			score = 60;
		} else if (minute <= 20160) {
			score = 0;
		} else {
			score = -50;
		}

		return score;
	}

	public int getStarByScore(int score) throws Exception {
		int star = 0;
		if (score <= -10) {
			star = 0;
		} else if (score > -10 && score <= 0) {
			star = 1;
		} else if (score > 0 && score <= 10) {
			star = 2;
		} else if (score > 10 && score <= 20) {
			star = 3;
		} else if (score > 20 && score <= 30) {
			star = 4;
		} else if (score > 30 && score <= 40) {
			star = 5;
		} else if (score > 40 && score <= 60) {
			star = 6;
		} else if (score > 60 && score <= 70) {
			star = 7;
		} else if (score > 70 && score <= 80) {
			star = 8;
		} else if (score > 80 && score <= 90) {
			star = 9;
		} else if (score > 90) {
			star = 10;
		}
		return star;
	}

	@Override
	public List<UserAreaModel> getUserAreaList(int userid) {
		return userDao.getUserAreaList(userid);
	}

	@Override
	public void updateUserAreaList(int userid, int[] list) {
		userDao.deleteUserAreaList(userid);

		if (list != null && list.length > 0) {
			List<UserAreaModel> areaList = new ArrayList<UserAreaModel>();
			for (int areaid : list) {
				UserAreaModel userModel = new UserAreaModel();
				userModel.setAreaid(areaid);
				userModel.setUserid(userid);
				areaList.add(userModel);
			}
			userDao.insertUserAreaList(areaList);
		}
	}

	@Override
	public List<UserCategoryModel> getUserCategoryList(int userid) {
		return userDao.getUserCategoryList(userid);
	}

	@Override
	public void updateUserCategoryList(int userid, int[] list) {
		userDao.deleteUserCategoryList(userid);

		if (list != null && list.length > 0) {
			List<UserCategoryModel> categoryList = new ArrayList<UserCategoryModel>();
			for (int categoryid : list) {
				UserCategoryModel userModel = new UserCategoryModel();
				userModel.setCategoryid(categoryid);
				userModel.setUserid(userid);
				categoryList.add(userModel);
			}
			userDao.insertUserCategoryList(categoryList);
		}
	}

}
